<?php

namespace App\Http\Controllers;

use App\Models\AnswerInfo;
use App\Helpers\Tools;
use App\Models\ChallengeLevel;
use App\Models\Member;
use App\Models\Title;
use App\Models\User;
use App\Services\WeChatService;
use Illuminate\Support\Facades\Redis;

class WeChatController extends ApiController
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function service()
    {
        $app = app('wechat.official_account');
        $app->server->push(function ($message) {
            return "欢迎关注 overtrue！";
        });

        return $app->server->serve();
    }

    /**
     * jssdk分享接口
     *
     */
    public function jssdkJson()
    {
        $wechat = new WeChatService();
        $url = request('url');

        if (!$url) {
            $url = env('APP_H5_URL') . '/';
        }

        $config = $wechat->jssdkJson($url);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://www.devdo.net");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);

        if ($output === FALSE) {
            echo $output;
            exit;
        }

        return $resource = [
            'error' => 0,
            'status' => 200,
            'data' => \Qiniu\json_decode($config)
        ];
    }

    /**
     * 网页授权
     *
     */
    public function oauth()
    {
        $wechat = new WeChatService();

        $type = request('type', 1);
        $params = request()->all();

        $oauth = $wechat->oauth($type, $params);

        if (empty($_SESSION['wechat_user'])) {
            return $oauth->redirect();
        }
    }

    /**
     * 授权回调页
     *
     */
    public function oauthCallBack()
    {
        $wechat = new WeChatService();
        $oauth = $wechat->oauth();

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $type = request('type', 1);
        if ($type == 1) {
            $page = 'index';
        } else if ($type == 3) {
            $page = 'room';
        } else if ($type == 5 || $type == 6) {
            $recordId = request('recordId');
            $page = 'answer/index.html';
        } else {
            $page = 'posetIndex';
        }

        if ($user) {
            $user = $user->toArray();

            if ($type != 5 && $type != 6) {
                # 
                // 验证该用户是否注册，如果未注册，先注册再跳转
                $res = unserialize(Redis::get('user:openid:' . $user['id']));

                if (!$res) {
                    $res = $this->register($user, $type);

                    if ($res) {
                        $url = env('APP_H5_URL') . "/#/$page?id=" . $res['id'];
                    } else {
                        return $this->response(Tools::error('注册失败，请重新注册'));
                    }
                } else {
                    $url = env('APP_H5_URL') . "/#/$page?id=" . $res['id'];
                }
            } else {
                // 判断有没注册过
                $res = unserialize(Redis::get('memberId:openid:' . $user['id']));

                if (!$res) {
                    $data['openid'] = $user['id'];
                    $data['nickname'] = $user['name'];
                    $data['avatar_url'] = $user['avatar'];
                    $data['province'] = $user['original']['province'];
                    $data['city'] = $user['original']['city'];
                    $data['created_at'] = date('Y-m-d H:i:s');
                    $data['updated_at'] = date('Y-m-d H:i:s');

                    $member = new Member();

                    $id = $member->insertGetId($data);

                    $title = new Title();
                    $title->member_id = $id;
                    $title->make = 0;
                    $title->sign = 0;
                    $title->victory = 0;
                    $title->challenge = 0;
                    $title->save();

                    $challengeLevel = new ChallengeLevel();
                    $challengeLevel->member_id = $id;
                    $challengeLevel->challenge1 = 0;
                    $challengeLevel->challenge2 = 0;
                    $challengeLevel->challenge3 = 0;
                    $challengeLevel->challenge4 = 0;
                    $challengeLevel->challenge5 = 0;
                    $challengeLevel->save();

                    $answerInfo = new AnswerInfo();
                    $answerInfo->member_id = $id;
                    $answerInfo->count = 0;
                    $answerInfo->timer = 0;
                    $answerInfo->residue = 1;
                    $answerInfo->save();

                    $data['id'] = $id;
                    Redis::set('memberId:openid:' . $user['id'], serialize($data));
                } else {
                    $id = $res['id'];
                }

                $url = env('APP_H5_URL') . "/$page?memberId=$id&type=$type&recordId=$recordId";
            }

            header("Location: $url");
        }
    }

    /**
     * 判断用户是否已经注册，如果未注册则注册
     *
     */
    public function register($user, $type)
    {
        $data = [];

        $data['openid'] = $user['id'];
        $data['number'] = $this->sendNumber();
        $data['nickname'] = $user['name'];
        $data['avatar_url'] = $user['avatar'];
        $data['wx_sex'] = $user['original']['sex'];
        $data['province'] = $user['original']['province'];
        $data['city'] = $user['original']['city'];
        $data['area'] = $type;
        $data['id'] = $this->sendUserId();
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        Redis::lpush('user:list', serialize($data));

        // 存入redis
        Redis::set('user:' . $data['id'], serialize($data));
        Redis::set('user:openid:' . $user['id'], serialize($data));
        Redis::set('user:number:' . $data['number'], serialize($data));

        return $data;
    }

    public function sendNumber()
    {
        if (Redis::exists('number:id')) {
            Redis::incr('number:id');
            return Redis::get('number:id');
        } else {
            $number = 30;
            ++$number;
            Redis::set('number:id', $number);
            return $number;
        }
    }

    public function sendUserId()
    {
        $key = 'is:user:id';
        if (Redis::exists($key)) {
            Redis::incr($key);
            return Redis::get($key);
        } else {
            $number = 30;
            ++$number;
            Redis::set($key, $number);
            return $number;
        }
    }

}
